<template>
    <div style="align-content: center; margin-left: 50px; margin-top: 20px">
        <van-image

            width="15rem"
            fit="cover"
            position="right"
            height="15rem"
            src="../src/assets/flower.jpg"
        />
    </div>
    <br/>
    <van-form @submit="onSubmit">

        <van-cell-group inset>
            <van-field
                    v-model="userAccount"
                    name="userAccount"
                    label="账号"
                    placeholder="请输入账号"
                    :rules="[{ required: true, message: '请填写用户名' }]"
            />
            <van-field
                    v-model="userPassword"
                    type="password"
                    name="userPassword"
                    label="密码"
                    placeholder="请输入密码"
                    :rules="[{ required: true, message: '请填写密码' }]"
            />
        </van-cell-group>
        <div style="margin: 16px;">
            <van-button round block type="primary" native-type="submit">
                登录
            </van-button>
        </div>
        <div style="margin: 16px;">
            <van-button round block type="primary" @click="register">
                注册
            </van-button>
        </div>
    </van-form>
</template>

<script setup lang="ts">
import imgUrl from './flower.jpg'

import {useRoute, useRouter} from "vue-router";
import {ref} from "vue";
import myAxios from "../plugins/myAxios";
import {showFailToast, showSuccessToast, showToast} from "vant";
import {useCache} from "../hooks/useCache.ts";
import {useAppStore} from "../store/modules/app.ts";

document.getElementById('hero-img').src = imgUrl
const router = useRouter();
const route = useRoute();

const userAccount = ref('');
const userPassword = ref('');

const register = () =>{
    router.push({
        path: "/user/register"
    })
}

const appStore = useAppStore();
const onSubmit = async () => {
    const res = await myAxios.post('/user/login', {
        userAccount: userAccount.value,
        userPassword: userPassword.value,
    })

    if (res.code === 0 && res.data) {
        showSuccessToast('登录成功');
        // 跳转到之前的页面
        const { wsCache } = useCache();
        wsCache.set(appStore.getUserInfo, res.data);
        const redirectUrl = route.query?.redirect as string ?? '/';
        window.location.href = redirectUrl;
    } else {
        showFailToast('登录失败');
    }
};

</script>

<style scoped>

</style>